// 初始化事件监听
const initializeEventListeners = () => {
  // 新建考试按钮
  const create_exam_btn = document.getElementById('create_exam_btn');
  create_exam_btn.addEventListener('click', () => {
    window.location.href ='/create_exams'
  });

  // 筛选和搜索
  const statusSelect = document.querySelector('select:nth-of-type(1)');
  const typeSelect = document.querySelector('select:nth-of-type(2)');
  const classSelect = document.querySelector('select:nth-of-type(3)');
  const searchInput = document.querySelector('input[type="text"]');

  [statusSelect, typeSelect, classSelect, searchInput].forEach(element => {
    element.addEventListener('change', loadExamList);
  });

  searchInput.addEventListener('input', debounce(loadExamList, 500));
};

// 防抖函数
const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

// 加载考试列表
const loadExamList = async () => {
  try {
    const statusSelect = document.querySelector('select:nth-of-type(1)');
    const typeSelect = document.querySelector('select:nth-of-type(2)');
    const classSelect = document.querySelector('select:nth-of-type(3)');
    const searchInput = document.querySelector('input[type="text"]');

    // 构建查询参数
    const params = new URLSearchParams();
    if (statusSelect.value !== '全部状态') params.append('status', statusSelect.value);
    if (typeSelect.value !== '全部类型') params.append('exam_type', typeSelect.value);
    if (classSelect.value !== '全部班级') params.append('class_id', classSelect.value);
    if (searchInput.value.trim()) params.append('keyword', searchInput.value.trim());

    // 发送请求
    const response = await fetch(`/api/exam_schedules?${params.toString()}`);
    const data = await response.json();

    if (data.error) {
      throw new Error(data.error);
    }

    // 渲染考试列表
    renderExamList(data.exams);
  } catch (error) {
    console.error('加载考试列表失败:', error);
    alert('加载考试列表失败，请稍后重试');
  }
};

// 渲染考试列表
const renderExamList = (exams) => {
  const examList = document.getElementById('exam-list');

  if (!exams || exams.length === 0) {
    examList.innerHTML = `
      <div class="bg-white rounded-xl p-8 card-shadow text-center">
        <i class="fa fa-info-circle text-4xl text-gray-300 mb-4"></i>
        <p class="text-gray-500">暂无符合条件的考试</p>
      </div>
    `;
    return;
  }

  examList.innerHTML = exams.map(exam => `
    <div class="bg-white rounded-xl card-shadow overflow-hidden hover:shadow-lg transition-shadow">
      <div class="p-5 border-b border-gray-100 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div class="flex items-start gap-4">
          <div class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center text-primary flex-shrink-0">
            <i class="fa fa-file-text-o text-xl"></i>
          </div>

          <div class="flex-1">
            <div class="flex flex-wrap items-center gap-2 mb-1">
              <h3 class="font-bold text-lg">${exam.exam_name}</h3>
              <span class="px-2 py-0.5 text-xs rounded-full bg-${exam.status_class}/20 text-${exam.status_class}">${exam.exam_status}</span>
              <span class="px-2 py-0.5 text-xs rounded-full bg-blue-100 text-blue-600">${exam.exam_type}</span>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-2 text-sm">
              <div class="flex items-center text-gray-600">
                <i class="fa fa-book text-gray-400 mr-2"></i>
                <span>学科：${exam.exam_subject}</span>
              </div>
              <div class="flex items-center text-gray-600">
                <i class="fa fa-users text-gray-400 mr-2"></i>
                <span>班级：${exam.class_names.join('、')}</span>
              </div>
              <div class="flex items-center text-gray-600">
                <i class="fa fa-clock-o text-gray-400 mr-2"></i>
                <span>时间：${exam.start_time}-${exam.end_time}</span>
              </div>
              <div class="flex items-center text-gray-600">
                <i class="fa fa-question-circle text-gray-400 mr-2"></i>
                <span>题目：满分${exam.total_score}分</span>
              </div>
              <div class="flex items-center text-gray-600">
                <i class="fa fa-user text-gray-400 mr-2"></i>
                <span>监考教师：${exam.teacher_name}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="flex gap-2 self-end md:self-auto">
          ${exam.exam_status === '未开始' ? 
            `<button class="btn-start flex items-center text-sm" data-exam-id="${exam.id}">
              <i class="fa fa-play mr-1"></i>开始考试
            </button>` : ''
          }
          <button class="btn-danger flex items-center text-sm" data-exam-id="${exam.id}">
            <i class="fa fa-trash mr-1"></i>删除
          </button>
        </div>
      </div>
    </div>
  `).join('');

  // 添加删除和开始考试的事件监听
  document.querySelectorAll('.btn-danger').forEach(btn => {
    btn.addEventListener('click', handleDeleteExam);
  });

  document.querySelectorAll('.btn-start').forEach(btn => {
    btn.addEventListener('click', handleStartExam);
  });
};

// 处理删除考试
const handleDeleteExam = async (event) => {
  const examId = event.currentTarget.getAttribute('data-exam-id');

  if (!confirm('确定要删除这个考试吗？此操作不可恢复。')) {
    return;
  }

  try {
    const response = await fetch(`/api/exam_schedules/${examId}`, {
      method: 'DELETE'
    });

    if (!response.ok) {
      throw new Error('删除考试失败');
    }

    alert('考试已删除');
    loadExamList(); // 重新加载列表
  } catch (error) {
    console.error('删除考试失败:', error);
    alert('删除考试失败，请稍后重试');
  }
};

// 处理开始考试
const handleStartExam = async (event) => {
  const examId = event.currentTarget.getAttribute('data-exam-id');

  if (!confirm('确定要开始这个考试吗？')) {
    return;
  }

  try {
    const response = await fetch(`/api/exam_schedules/${examId}/start`, {
      method: 'POST'
    });

    if (!response.ok) {
      throw new Error('开始考试失败');
    }

    alert('考试已开始');
    loadExamList(); // 重新加载列表
  } catch (error) {
    console.error('开始考试失败:', error);
    alert('开始考试失败，请稍后重试');
  }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
  initializeEventListeners();
  loadExamList();
});
